<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\BaofuCard;
use App\Models\BaofuPay;
use App\Models\Goods;
use App\Models\GoodsCustomRent;
use App\Models\GoodsSetmeal;
use App\Models\GoodsSpec;
use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderDepositRechargeLog;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderLog;
use App\Models\OrderRate;
use App\Models\OrderRemark;
use App\Models\OtherOrder;
use App\Models\OtherOrderAllocate;
use App\Models\OtherWithholdLog;
use App\Models\ShopSms;
use App\Models\ShopUser;
use App\Models\SmsTemplate;
use App\Models\Config;
use App\Models\AuthenticLog;
use App\Models\WechatMember;
use App\Services\AlipayService;
use App\Services\AntchainService;
use App\Services\ChargeService;
use App\Services\BaofuService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\NotarizeService;
use App\Services\OrderService;
use App\Services\OtherCallbacksService;
use App\Services\OtherNotifyService;
use App\Services\OttService;
use App\Services\ZlbService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NoticeController
{

    /**
     * e签宝合同签署回调-微信
     */
    public function esignNotify(Request $request){
        $request_data = $request->all();
        WechatService::requestLog('e签宝合同签署回调-微信','',$request_data);
        $flow_id = $request_data['flowId'];
        $order = Order::from('sp_order_2 as o')
            ->where('o.flow_id',$flow_id)
            ->leftjoin('sp_member_2 as u','o.uid','u.id')
            ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
            ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
            ->select(
                'o.id','o.trade_no','o.begin_time','o.zulinbao_order_id','o.end_time','o.pact_url_3','o.pact_url','o.uid','o.seller_id','o.is_insurance_choose',
                'o.flow_id','o.mobile','o.user_email','o.sign_num','o.address','o.rent_total','o.month_total','o.amount','o.realname','o.rent_total',
                'o.foregift','o.status','o.prov','o.city','o.area','o.sign_status','o.is_rent_choose'
                ,'o.create_time'
                ,'u.ant_user_id','u.mobile as user_mobile','u.id as x_user_id','u.cert_name','u.user_id','u.cert_no','u.esign_user_id'
                ,'u.idcard_front','u.idcard_back','og.id as order_goods_id ','og.pact_type','og.is_buy_out','og.goods_title','og.setmeal_title',
                'og.lease_set','og.setmeal_price','og.setmeal_foregift','o.prepayment_total',
                'og.goods_id','og.setmeal_id','og.id as order_goods_id','og.spec_id','og.lease_price','og.lease_time','og.website_price','og.start_date'
                ,'su.mechanism','su.faname','su.shopname','su.contact_tel','su.company','su.company_area','su.companyid','su.id as shop_user_id'
                ,'su.ant_user_id as mer_ant_id','o.sign_no','su.esign_seal_id','su.ant_seal_id','o.prepayment_total' ,'g.new_grade')
            ->first();
        $order = $order ? $order->toArray() : [];

        if(!empty($order)){
            if($order['sign_status'] == EsignService::ESIGN_STATUS_DRAFT || $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING){

                if($request_data['action'] == 'SIGN_FLOW_FINISH'){
                    //合同下载
                    $return_content = EsignService::downloadDocument($flow_id);
                    if($return_content && !empty($return_content['fileUrl'])){
                        $fileUrl = $return_content['fileUrl'];
                        $fileName = $flow_id.".pdf";
                        $file = file_get_contents($fileUrl);
                        $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

                        file_put_contents($path,$file);
                        $uploud_res = AlipayService::upload($fileName,$path);
                        if($uploud_res['status']){
                            if(file_exists($path)){
                                unlink($path);
                            }
                        }
                        $order_sign['pact_url'] = $fileName;
                        $order_sign['sign_status']  = EsignService::ESIGN_STATUS_FINISH;
                        $order_sign['status']= OrderService::ORDER_STATUS_SIGN_NOTPAY;
                        Order::where('id',$order['id'])->update($order_sign);

//                        $order['pact_url'] = $fileName;
//                        NotarizeService::uploadOrderInfo($order);


                        return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
                    }else{
                        return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
                    }
                }
            }else{
                return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
            }
        }else{
            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
        }
    }
    /**
     * 微信支付回调
     */
    public function wechatPayNotify(Request $request){

        $data = WechatService::notices();
        WechatService::requestLog('微信支付回调','',$data);

        if($data['return_code'] == 'SUCCESS'){
            $leaseId = explode(',',$data['attach']);//支付lease_id
            $order_id = $leaseId[0];
            $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->select('o.id','o.uid','o.pact_url','o.sign_status','o.id','o.seller_id','o.realname',
                    'o.trade_no','o.mobile','o.other_order_id','o.other_user_id','o.rent_total','m.openId','o.create_time',
                    'og.goods_title', 'og.imgurl', 'og.setmeal_title','og.imgurl','o.is_skip','m.cert_name','m.cert_no',
                    'm.mobile','og.pact_type','o.month_total','o.is_renewal','o.parent_order_no')->first();
            $order=obToArray($order);
            unset($leaseId[0]);
            $leaseSave['trade_no']     = $order['trade_no'];
            $leaseSave['out_order_no'] = $data['transaction_id'];
            $leaseSave['pay_time']  = time();
            $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
            $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_WECHAT;

            //更改已还租期
            Order::where(['id' => $order['id']])->increment('month_paid',count($leaseId));

            $orderLease = OrderLease::whereIn('id',$leaseId)->select('id','which_period','rent','paid_rent')->get();
            $orderLease = obToArray($orderLease);
            $leaseTotal = [];
            $zlbLeaseId = [];
            foreach ($orderLease as $lease){
                //更新账单数据
                OrderLease::where('id',$lease['id'])->update($leaseSave);
                if($lease['which_period'] == 1){
                    if($order['is_renewal'] == Order::ORDER_NOT_RENEWAL){
                        if($order['is_skip'] == Order::RISK_SKIP_YES){
                            $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                        }else{
                            $risk_res = ChargeService::RiskCreditUse($order['seller_id'],$order['id'],$order['cert_name'],$order['cert_no'],$order['mobile'],1);
                            $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                        }
                        $user_order_count = Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                        Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count'=>$user_order_count]);
                    }else{//续租订单不发货，第一期扣款成功订单状态直接变为租用中
                        if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                            $arr['status'] = OrderService::ORDER_STATUS_TOBE_RETURNED;
                        }else{
                            $arr['status'] = OrderService::ORDER_STATUS_CONFIRM_GOODS;
                        }
                    }
                    $arr['pay_time']=time();
                    $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                    Order::where(['id' => $order['id']])->update($arr);
                    //短信通知
                    ShopSms::orderPlaceSendToShop($order['seller_id'],$order['realname'],$order['trade_no']);
                    ShopSms::orderPaidSendToUser($order['seller_id'],$order['realname'],$order['trade_no'],$lease['rent'],$order['mobile'],$order['id']);
                }else{
                    $zlbLeaseId[] = $lease['id'];
                    if($order['pact_type'] != GoodsService::GOODS_PACT_TYPE_GIVE){
                        //所有租期已全部支付，状态改为待归还
                        if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                            Order::where(['id' => $order['id']])->update(['status'=>OrderService::ORDER_STATUS_TOBE_RETURNED,'pay_time'=>time()]);
                        }
                    }
                }

                OtherWithholdLog::orderWithholdLog($order['trade_no'],$lease['id'],$data['out_trade_no'],$order['trade_no'],$data,OtherWithholdLog::PAY_TYPE_WXPAY,true,1);
                $leaseTotal[$lease['id']] = bcsub($lease['rent'],$lease['paid_rent'],2);
            }
            //更新实付款金额

            if($leaseTotal = computeDiscount($leaseTotal,bcdiv($data['total_fee'],100,2))){
                foreach ($leaseTotal as $k=>$value){
                    //更新账单数据-商家实际收金额
                    OrderLease::where(["id"=>$k])->increment('paid_rent',$value);
                }
            }
            //检测逾期订单状态
            if($status = Order::checkOrderOverdueStatus($order['id'])){
                Order::where(['id' => $order['id']])->update(['status'=>$status,'pay_time'=>time()]);
            }

            $order['out_order_no'] = $data['transaction_id'];
            if($order&&$order['openId']){
                WechatService::upload_shipping_info_lease($order,implode(',',array_column($orderLease,'which_period')));
            }
            WechatService::requestLog('微信支付成功-期数id','',$leaseId);
            CreditCallService::repayInvestData($order['id'],$lease['id']);//上报征信-还款

            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名错误]]></return_msg></xml>';
        }



    }


    /**
     * e签宝人脸识别回调
     */
    public function faceAuthNotice(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('e签宝人脸识别回调微信','',$request_data);

        $flow_id = $request_data['flowId'];
        $status = $request_data['status'];
        $contextId = $request_data['contextId'];
        if($status){
            $log = AuthenticLog::where(['certify_id'=>$flow_id])->orderBy('id','desc')->select('id','order_id','cert_no','cert_name','idcard_front','idcard_back')->first();
            $log = obToArray($log);
            $order_data = Order::where('id',$log['order_id'])->select('id','trade_no','mobile','seller_id','realname')->first();
            ShopSms::orderAuditSms($order_data['seller_id'],$order_data['trade_no'],$order_data['mobile']);
            if($log){
                $update = [];
                $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;
                $request_data['time']=date('Ymd H:i:s',time());
                $update['result'] = json_encode($request_data);
                AuthenticLog::where(['id'=>$log['id']])->update($update);

                //更新数据
                WechatMember::where(['id'=>$contextId])->update(['idcard_front'=>$log['idcard_front'],'idcard_back'=>$log['idcard_back'],'cert_name'=>$log['cert_name'],'cert_no'=>$log['cert_no']]);

                $update_data = [];
                $update_data['status'] = OrderService::ORDER_STATUS_SIGN_NOCHECK;

                Order::where('id',$log['order_id'])->update($update_data);

            }
        }


        return $request_data;
    }

}
